package com.chz.SupermarketMS.controllers;

import com.chz.SupermarketMS.dao.*;
import com.chz.SupermarketMS.dto.ChartData;
import com.chz.SupermarketMS.entities.*;
import com.chz.SupermarketMS.service.CommodityService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class HomeController {

    @Value("${version}")
    private String version;

    @Autowired
    CommodityService commodityService;

    @Autowired
    KindRepository kindRepository;


    @GetMapping("/")
    public String displayHome(Model model) throws JsonProcessingException {

        model.addAttribute("versionNumber",version);

        List<Commodity> commodities = commodityService.findAll();
        model.addAttribute("commodities",commodities);

        List<ChartData> kindTypeData= kindRepository.getKindType();
        ObjectMapper objectMapper= new ObjectMapper();
        String jsonString=objectMapper.writeValueAsString(kindTypeData);
        model.addAttribute("kindTypeData",jsonString);

        return "main/home";
    }

}
